package com.tmac.dynamic_proxy_hook;

import android.app.Activity;
import android.app.Instrumentation;

import com.tmac.library.ReflectUtils;

import java.lang.reflect.Field;

public class ProxyHookHelper {
    public static void hookContextMethod(){
        try {
            //获取到具体activityThread
            Class<?> activityThreadClass = Class.forName("android.app.ActivityThread");
            Field sCurrentActivityThreadFiled = ReflectUtils.getField(activityThreadClass, "sCurrentActivityThread");
            sCurrentActivityThreadFiled.setAccessible(true);
            Object activityThread = sCurrentActivityThreadFiled.get(activityThreadClass);

            //获取Instrumentation
            Field mInstrumentationFiled = ReflectUtils.getField(activityThreadClass, "mInstrumentation");
            mInstrumentationFiled.setAccessible(true);
            Instrumentation instrumentation = (Instrumentation) mInstrumentationFiled.get(activityThread);

            //执行我们的代理对象
            ProxyInstrumentation proxyInstrumentation = new ProxyInstrumentation(instrumentation);
            mInstrumentationFiled.set(activityThread,proxyInstrumentation);


        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    public static void hookActivityMethod(Activity activity){
        try {
            Class<? extends Activity> aClass = activity.getClass();
            Field mInstrumentationFiled = ReflectUtils.getField(aClass, "mInstrumentation");
            mInstrumentationFiled.setAccessible(true);
            Instrumentation instrumentation = (Instrumentation) mInstrumentationFiled.get(activity);

            //执行我们的代理对象
            ProxyInstrumentation proxyInstrumentation = new ProxyInstrumentation(instrumentation);
            mInstrumentationFiled.set(activity,proxyInstrumentation);
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }

    }
}
